library flutter_project_tool;

import 'dart:io';

import 'package:args/args.dart';
import 'package:xml/xml.dart';
import 'package:yaml/yaml.dart';

part 'constants.dart';
part 'constants_updater.dart';
part 'ios.dart';
part 'android.dart';

void updateInfo(ArgResults options) {
  var config = getConfig(configFile: options['path']);
  updateInfoByConfig(options, config);
}

void updateInfoByConfig(ArgResults options, Map<String, dynamic> config) {
  String platform = options['platform'] ?? 'ios';
  String appName;
  String umengKey;
  String version;
  String useProtocol;
  String privacyProtocol;
  String platformKey;
  if (platform != 'ios') {
    final androidConfig = config['android'][options['platform']];
    appName = androidConfig['name'];
    umengKey = androidConfig['umeng_key'];
    version = androidConfig['version'];
    useProtocol = androidConfig['use_protocol'];
    privacyProtocol = androidConfig['privacy_protocol'];
    platformKey = androidConfig['platform'];
  } else {
    appName = config['ios']['name'];
    umengKey = config['ios']['umeng_key'];
    version = config['ios']['version'];
    useProtocol = config['ios']['use_protocol'];
    privacyProtocol = config['ios']['privacy_protocol'];
    platformKey = config['ios']['platform'];
  }

  updateConstants(
    universalLinkHost: config['universal_link_host'],
    appName: appName,
    appId: config['ios']['app_id'],
    urlScheme: config['url_scheme'],
    qqAppId: config['qq_app_id'],
    qqAppKey: config['qq_app_key'],
    wxAppId: config['wx_app_id'],
    wxSecret: config['wx_app_secret'],
    umengKey: umengKey,
    version: version,
    jpushKey: config['jpush_key'],
    platform: platformKey,
    useProtocol: useProtocol,
    privacyProtocol: privacyProtocol,
    appKey: config['app_key'],
  );
  if (platform != 'ios') {
    updateAndroidInfo(options, config);
  } else {
    updateIosInfo(options, config);
  }
}

Map<String, dynamic> getConfig({String? configFile}) {
  String filePath;
  if (configFile != null && File(configFile).existsSync()) {
    filePath = configFile;
  } else if (File('flutter_project_tool.yaml').existsSync()) {
    filePath = 'flutter_project_tool.yaml';
  } else {
    filePath = 'pubspec.yaml';
  }

  final Map yamlMap = loadYaml(File(filePath).readAsStringSync());

  if (yamlMap['flutter_project_tool'] is! Map) {
    throw Exception('Your `$filePath` file does not contain a '
        '`flutter_project_tool` section.');
  }

  // yamlMap has the type YamlMap, which has several unwanted side effects
  final config = <String, dynamic>{};
  for (MapEntry<dynamic, dynamic> entry
      in yamlMap['flutter_project_tool'].entries) {
    if (entry.value is YamlList) {
      var list = <String>[];
      (entry.value as YamlList).forEach((dynamic value) {
        if (value is String) {
          list.add(value);
        }
      });
      config[entry.key] = list;
    } else {
      config[entry.key] = entry.value;
    }
  }
  return config;
}
